<?php
namespace app\dboard\controller;
use think\captcha;
use think\facade\Cookie;
use think\facade\Session;
use think\facade\Url;
use think\Db;
use app\api\logic\Publics;
class Teacher extends Base
{
    public function initialize() {
        parent::initialize();
        $returnUrl=Url::build('dboard/mlogin/sign');
        if(!isset($this->AdminAccount['AdminID']) || intval($this->AdminAccount['AdminID'])<=0 || !isset($this->AdminAccount['sid'])){
            if($this->request->isAjax()){
                return $this->print_result(['Code'=>9999,'Msg'=>'请登录']);
            }
            return $this->redirect($returnUrl);
        }
    }
    public function add_teacher(){
        return view('teacher/add_teacher');
    }
    public function edit_teacher(){
        return view('teacher/edit_teacher');
    }
    public function lists(){
        $input = $this->request->param(false);
        $id = isset($this->AdminAccount['sid'])?$this->AdminAccount['sid']:0;
        if (!$id) {
            return $this->print_result(['Code'=>1,'Msg'=>'缺少必要参数']);
        }
        $store = Db::name('store')->where(['id'=>$id])->find();
        // 判断教师数量有没有达到门店限定
        $teacher_num = Db::name('teacher')->where(['sid'=>$id,'status'=>1])->count();
        $this->assign('add_teacher',$store['teacher_num']>$teacher_num?1:0);
        return view('teacher/lists');
    }
   public function ajaxList(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $input = $this->request->param(false);
        $page_limit      = isset($input['length'])?$input['length']:10;
        $page_start      = isset($input['start'])?$input['start']:0;
        $p = 1;
        if ($page_start > 0) {
            $p = ceil($page_start / ($page_limit - 1));
        }
        $sid = isset($input['sid'])?$input['sid']:0;
        if (!$sid) {
          $this->res_data['Msg'] = "缺少必填信息";
          return $this->res_data;
        }
        $store= Db::name('store')->where([['id','=',$sid]])->find();
        if (!$store) {
          $this->res_data['Msg'] = "无此门店";
          return $this->res_data;
        }
        $where = [];
        $where[] = ['sid','=',$sid];
        $where[] = ['status','=',1];
        $field = '*';
        $count=Db::name('teacher')->where($where)->count();
        $list  = Db::name('teacher')
              ->field($field)
              ->where($where)
              ->order('ordernum asc')
              ->limit($page_start, $page_limit)->select();
        foreach($list as $k=>$v){
          $list[$k]['cover'] = get_basecover_img($v['avatar']);
        }
        
        $this->res_data['Msg']='OK';
        $this->res_data['Code']=0;
        $this->res_data['Data']=['teacher'=>$list,'Data'=>$list,'recordsTotal'=>$count];
        return $this->print_result($this->res_data);
   }
    public function infoData(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $input = $this->request->param(false);
        $id = isset($input['tid'])?$input['tid']:0;
        if(!$id){
            $this->res_data['Msg'] = '参数有误';
            return $this->print_result($this->res_data);
        }
        $where = [];
        $where[] = ['id','=',$id];
        $info = Db::name('teacher')
                ->where($where)
                ->find();
        if($info['avatar'])
          $info['cover'] = get_basecover_img($info['avatar']);

        $this->res_data['Msg']='OK';
        $this->res_data['Code']=0;
        $this->res_data['Data']=['teacher'=>$info];
        return $this->print_result($this->res_data);
   }
   public function doCreateTeacher(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($result);
        }
        $param    = $this->request->param(false);
        $teacher= Controller('Teacher', 'logic');
        $result            = $teacher->create($param);
        return $this->print_result($result);
   }
   public function editTeacherinfo(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($result);
        }
        $param    = $this->request->param(false);
        $teacher= Controller('Teacher', 'logic');
        $result            = $teacher->edit($param);
        return $this->print_result($result);
   }
   public function updateTeacher(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($result);
        }
        $param    = $this->request->param(false);
        $teacher= Controller('Teacher', 'logic');
        $result            = $teacher->updateTeacher($param);
        return $this->print_result($result);
   }

   public function teacherList()
   {
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($result);
        }
        $param    = $this->request->param(false);
        $sid = isset($param['sid'])?$param['sid']:0;
        if (!$sid) {
          $this->res_data['Msg'] = "缺少必填信息";
          return $this->res_data;
        }
        $list  = Db::name('teacher')
              ->field('id,name')
              ->where(['status'=>1,'sid'=>$sid])
              ->order('id desc')->select();
        $this->res_data['Msg']='OK';
        $this->res_data['Code']=0;
        $this->res_data['Data']=$list;
        return $this->res_data;
   }

   public function change_course()
   {
        if ($this->request->isPost()) {
          $input = $this->request->param(false);
          $sid = isset($input['sid'])?intval($input['sid']):0;
          $course_id = isset($input['course_id'])?intval($input['course_id']):0;
          $classtime_id = isset($input['classtime_id'])?intval($input['classtime_id']):0;
          $teacher_id = isset($input['teacher_id'])?intval($input['teacher_id']):0;
          $classroom_id = isset($input['classroom_id'])?intval($input['classroom_id']):0;
          $begin_time = isset($input['begin_time'])?trim($input['begin_time']):'';
          $end_time = isset($input['end_time'])?trim($input['end_time']):'';
          if (!$sid || !$course_id || !$classtime_id || !$begin_time || !$end_time) {
            $this->res_data['Msg'] = "缺少必填信息";
            return $this->res_data;
          }
          $classtime = Db::name('classtime')->where(['course_id'=>$course_id,'id'=>$classtime_id,'status'=>1])->find();
          if (!$classtime) {
            $this->res_data['Msg'] = "不存在课时信息";
            return $this->res_data;
          }
          if ($teacher_id) {
            $teacher = Db::name('teacher')->where(['id'=>$teacher_id,'status'=>1])->find();
            if (!$teacher) {
              $this->res_data['Msg'] = "不存在上课的老师";
              return $this->res_data;
            }
          }
          if ($classroom_id) {
            $classroom = Db::name('classroom')->where(['id'=>$classroom_id,'status'=>1])->find();
            if (!$classroom) {
              $this->res_data['Msg'] = "不存在上课的教室";
              return $this->res_data;
            }
          }
          $data['classtime_id'] = $classtime_id;
          $data['teacher_id'] = $teacher_id;
          $data['teacher_name'] = $teacher['name'];
          $data['classroom_id'] = $classroom_id;
          $data['classroom_name'] = $classroom['name'];
          $data['begin_time'] = strtotime($begin_time);
          $data['end_time'] = strtotime($end_time);
          $data['status'] = 1;
          $data['createtime'] = time();
          Db::startTrans();
          // try {
            $insert_id = Db::name('course_change')->insertGetId($data);
            if (!$insert_id) {
              Db::rollBack();
              $this->res_data['Msg'] = "调课有误";
              return $this->res_data;
            }
            $is_update = Db::name('classtime')->where('id',$classtime_id)->update(['status'=>2,'updatetime'=>time()]);
            if (!$is_update) {
              Db::rollBack();
              $this->res_data['Msg'] = "调课有误";
              return $this->res_data;
            }
            $classtime_data['course_id'] = $course_id;
            $classtime_data['begin_time'] = strtotime($begin_time);
            $classtime_data['end_time'] = strtotime($end_time);
            $classtime_data['status'] = 1;
            $classtime_data['createtime'] = time();
            $classtime_data['no'] = $classtime['no'];
            $classtime_data['remark'] = $classtime['remark'];
            $is_insert = Db::name('classtime')->insertGetId($classtime_data);
            if (!$is_insert) {
              Db::rollBack();
              $this->res_data['Msg'] = "调课有误";
              return $this->res_data;
            }
            // 调课通知
            $template_id = 'Ui7x3g96aHDGpUDI37o9wBAvkQwXvpYXm6bNNXO0Cl8';
            $page = 'orderPackages/pages/myChild/myClassTime?notice=1&sid='.$sid;
            $PublicsLogic = new Publics();
            $course = Db::name('course')->where(['id'=>$course_id])->field('*')->find();
            $students = Db::name('user_course')->alias('uc')->field('u.name,u.fwhopenid')->leftJoin('user u','u.id=uc.user_id')->where([['uc.course_id','=',$course['id']],['uc.status','in',[1,2]]])->select();
            if ($students) {
              foreach ($students as $stu) {
                if (isset($stu['fwhopenid']) && $stu['fwhopenid']) {
                  $openid = $stu['fwhopenid'];
                  $data = [
                      'first' => ['value' => '你好！【'.$course['name'].'】时间调整通知，请注意。'],
                      'keyword1' => ['value' => $classroom['name']],
                      'keyword2' => ['value' => date('Y-m-d H:i',$classtime['begin_time'])],
                      'keyword3' => ['value' => $begin_time],
                      'remark' => ['value' => '请家长及时查收确认调课情况。'],
                  ];
                  $res = $PublicsLogic->send_template_message($template_id, $page, $data, $openid);
                }
              }
            }
            Db::commit();
            $this->res_data['Msg']='OK';
            $this->res_data['Code']=0;
            return $this->res_data;
          // } catch (\Exception $e) {
          //   Db::rollBack();
          //   $this->res_data['Msg'] = "调课有误";
          //   return $this->res_data;
          // }

        }
        $input = $this->request->param(false);
        $id = isset($input['tid'])?$input['tid']:0;// 老师id
        if(!$id){
            $this->res_data['Msg'] = '参数有误';
            return $this->print_result($this->res_data);
        }
        $course = Db::name('course')->where(['sid'=>$this->AdminAccount['sid'],'status'=>1,'teacher_id'=>$id])->field('*')->select();
        $teacher = Db::name('teacher')->where(['sid'=>$this->AdminAccount['sid'],'status'=>1])->select();
        $classroom = Db::name('classroom')->where(['sid'=>$this->AdminAccount['sid'],'status'=>1])->select();
        $this->assign('course_list',$course);
        $this->assign('teacher',$teacher);
        $this->assign('classroom',$classroom);
        return view('teacher/change_course');
   }
}
